package com.cloud.servicesms.filter;

import com.cloud.internalcommon.dto.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 服务限流
 */
@Component
@SuppressWarnings("all")
public class LimitFilter implements Filter {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * guvava 自带的令牌桶
     */
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(2);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (RATE_LIMITER.tryAcquire()){
            //获取到令牌了，那么开始业务请求
            chain.doFilter(request, response);
        }else {
            //没有拿到令牌，走限流逻辑
            ResponseResult<Object> responseBody = ResponseResult.instance().setCode(HttpStatus.TOO_MANY_REQUESTS.value()).setMessage("请求过多");

            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(responseBody));
            writer.close();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
